package com.lqd.mall.gateway.filter;

import com.alibaba.fastjson.JSONObject;
import com.lqd.mall.basis.code.CommonCode;
import com.lqd.mall.basis.code.CustomCode;
import com.lqd.mall.basis.code.ResultCode;
import com.lqd.mall.basis.constant.CacheConstants;
import com.lqd.mall.basis.constant.SecurityConstants;
import com.lqd.mall.basis.constant.TokenConstants;
import com.lqd.mall.basis.exception.ExceptionCast;
import com.lqd.mall.basis.utils.JwtUtils;
import com.lqd.mall.basis.utils.ServletUtils;
import com.lqd.mall.basis.utils.StringUtils;
import com.lqd.mall.gateway.config.properties.IgnoreWhiteProperties;
import com.lqd.mall.redis.utils.RedisUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;

/**
 * @author 零起点
 * @create 2022-03-19 0:15
 */
@Slf4j
@Component
public class AuthFilter implements GlobalFilter, Ordered {

    @Resource
    IgnoreWhiteProperties ignoreWhiteProperties;


    @Autowired
    RedisUtils redisUtils;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

     ServerHttpRequest request = exchange.getRequest();

        ServerHttpRequest.Builder mutate = request.mutate();
        // 获取到访问路径
        String path = request.getURI().getPath();
        if (StringUtils.matches(path, ignoreWhiteProperties.getWhites())) {
            return chain.filter(exchange);
        }
        String token = getToken(request);
        if (StringUtils.isEmpty(token)) {
            return    webFluxResponseWriter(exchange, CommonCode.UNAUTHENTICATED);

        }
        Claims claims = JwtUtils.parseToken(token);

        if (claims == null) {
           return   webFluxResponseWriter(exchange, new CustomCode(false,401,"令牌已过期或验证不正确"));

        }
        String userkey = JwtUtils.getUserKey(claims);
        Boolean islogin = redisUtils.hasKey(getTokenKey(userkey));
        if (!islogin) {
            return   webFluxResponseWriter(exchange, new CustomCode(false,401,"登录状态已过期"));
        }
        String userid = JwtUtils.getUserId(claims);
        String username = JwtUtils.getUserName(claims);
        if (StringUtils.isEmpty(userid) || StringUtils.isEmpty(username)) {
            ExceptionCast.cast("令牌验证失败");
        }

        // 设置用户信息到请求
        addHeader(mutate, SecurityConstants.USER_KEY, userkey);
        addHeader(mutate, SecurityConstants.DETAILS_USER_ID, userid);
        addHeader(mutate, SecurityConstants.DETAILS_USERNAME, username);
        // 内部请求来源参数清除
        removeHeader(mutate, SecurityConstants.FROM_SOURCE);
        return chain.filter(exchange.mutate().request(mutate.build()).build());
    }


    @Override
    public int getOrder() {
        return -200;
    }


    private void removeHeader(ServerHttpRequest.Builder mutate, String name) {
        mutate.headers(httpHeaders -> httpHeaders.remove(name)).build();
    }

    private void addHeader(ServerHttpRequest.Builder mutate, String name, Object value) {
        if (value == null) {
            return;
        }
        String valueStr = value.toString();
        String valueEncode = ServletUtils.urlEncode(valueStr);
        mutate.header(name, valueEncode);
    }

    /**
     * 获取缓存key
     */
    private String getTokenKey(String token) {
        return CacheConstants.LOGIN_TOKEN_KEY + token;
    }

    /**
     * 获取请求token
     */
    private String getToken(ServerHttpRequest request) {
        String token = request.getHeaders().getFirst(TokenConstants.AUTHENTICATION);
        // 如果前端设置了令牌前缀，则裁剪掉前缀
        if (StringUtils.isNotEmpty(token) && token.startsWith(TokenConstants.PREFIX)) {
            token = token.replaceFirst(TokenConstants.PREFIX, StringUtils.EMPTY);
        }
        return token;
    }

    /**
     * 设置webflux模型响应
     *
     * @param response             ServerHttpResponse
     * @param applicationJsonValue
     * @param status               http状态码
     * @param value                响应内容
     * @param code                 响应状态码
     * @return Mono<Void>
     */
    public static Mono<Void> webFluxResponseWriter(ServerHttpResponse response, String contentType, HttpStatus status,
                                                   Object value, int code) {

        response.setStatusCode(status);
        response.getHeaders().add(HttpHeaders.CONTENT_TYPE, contentType);
        CustomCode result =new CustomCode(false,code, value.toString());
        DataBuffer dataBuffer = response.bufferFactory().wrap(JSONObject.toJSONString(result)
                .getBytes(StandardCharsets.UTF_8));
         return response.writeWith(Mono.just(dataBuffer));
    }

    private Mono<Void> webFluxResponseWriter(ServerWebExchange exchange, ResultCode code) {
        return webFluxResponseWriter(exchange.getResponse(), MediaType.APPLICATION_JSON_VALUE, HttpStatus.OK,
                code.message(), code.code());
    }

    private Mono<Void> webFluxResponseWriter(ServerWebExchange exchange, String messages) {
        return webFluxResponseWriter(exchange.getResponse(), MediaType.APPLICATION_JSON_VALUE, HttpStatus.OK, messages,
                500);
    }
}
